/**
 *    Copyright (c) [2022] [中和农信]
 *    rabbit-mq-plus is licensed under Mulan PSL v2.
 *    You can use this software according to the terms and conditions of the Mulan PSL v2.
 *    You may obtain a copy of Mulan PSL v2 at:
 *             http://license.coscl.org.cn/MulanPSL2
 *    THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *    See the Mulan PSL v2 for more details.
 *
 */
package com.cfpamf.athean.rabbit.mq.plus.producer.core.event.listener;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

import com.cfpamf.athean.rabbit.mq.plus.common.constant.BusinessConstants;
import com.cfpamf.athean.rabbit.mq.plus.producer.core.event.RabbitMqPlusProducerMessageSendEvent;
import com.cfpamf.athean.rabbit.mq.plus.service.RabbitMqPlusProducerService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class RabbitMqPlusProducerMessageSendEventListener {

    @Resource
    private ThreadPoolTaskExecutor rabbitMqThreadPool;

    @Autowired
    private RabbitMqPlusProducerService rabbitMqPlusProducerService;

    @Async("rabbitMqPlusThreadPool")
    @TransactionalEventListener
    public void listener(RabbitMqPlusProducerMessageSendEvent event) throws Exception {
        try {
            if (log.isDebugEnabled()) {
                log.debug("[rabbitMqPlus]生产者消息发送， 事物记录提交成功开始发送消息。{} {}", event.getRabbitMqPlusMessageDTO().getEventNo(),
                    event.getRabbitMqPlusMessageDTO().getEventTypeCode());
            }
            rabbitMqPlusProducerService.sendMessage(event.getRabbitMqPlusMessageDTO(), BusinessConstants.ZERO);
        } catch (Exception e) {
            log.error("[rabbitMqPlus]生产者消息发送， 事物记录提交成功开始发送消息。{} {} 异常", event.getRabbitMqPlusMessageDTO().getEventNo(),
                event.getRabbitMqPlusMessageDTO().getEventTypeCode(), e);
        }
    }

}
